import 'package:flutter/foundation.dart';

/// 帖子类型枚举
enum PostType {
  discussion,  // 讨论
  question,    // 提问
  sharing,     // 分享
  showcase,    // 作品展示
  news,        // 资讯
  event,       // 活动
}

/// 帖子状态枚举
enum PostStatus {
  published,   // 已发布
  draft,       // 草稿
  hidden,      // 隐藏
  deleted,     // 已删除
}

/// 用户信息
class CommunityUser {
  final String id;
  final String username;
  final String avatar;
  final String nickname;
  final String bio;
  final int level;         // 用户等级
  final int points;        // 积分
  final int postCount;     // 发帖数
  final int likeCount;     // 获赞数
  final int followCount;   // 关注数
  final int fanCount;      // 粉丝数
  final List<String> badges; // 徽章
  final DateTime joinDate;
  final bool isVerified;   // 是否认证
  final bool isOnline;     // 是否在线
  final bool isFollowing;  // 是否已关注

  const CommunityUser({
    required this.id,
    required this.username,
    this.avatar = '',
    this.nickname = '',
    this.bio = '',
    this.level = 1,
    this.points = 0,
    this.postCount = 0,
    this.likeCount = 0,
    this.followCount = 0,
    this.fanCount = 0,
    this.badges = const [],
    required this.joinDate,
    this.isVerified = false,
    this.isOnline = false,
    this.isFollowing = false,
  });

  factory CommunityUser.fromJson(Map<String, dynamic> json) {
    return CommunityUser(
      id: json['id'] ?? '',
      username: json['username'] ?? '',
      avatar: json['avatar'] ?? '',
      nickname: json['nickname'] ?? '',
      bio: json['bio'] ?? '',
      level: json['level'] ?? 1,
      points: json['points'] ?? 0,
      postCount: json['post_count'] ?? 0,
      likeCount: json['like_count'] ?? 0,
      followCount: json['follow_count'] ?? 0,
      fanCount: json['fan_count'] ?? 0,
      badges: List<String>.from(json['badges'] ?? []),
      joinDate: DateTime.parse(json['join_date'] ?? DateTime.now().toIso8601String()),
      isVerified: json['is_verified'] ?? false,
      isOnline: json['is_online'] ?? false,
      isFollowing: json['is_following'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'username': username,
      'avatar': avatar,
      'nickname': nickname,
      'bio': bio,
      'level': level,
      'points': points,
      'post_count': postCount,
      'like_count': likeCount,
      'follow_count': followCount,
      'fan_count': fanCount,
      'badges': badges,
      'join_date': joinDate.toIso8601String(),
      'is_verified': isVerified,
      'is_online': isOnline,
      'is_following': isFollowing,
    };
  }

  CommunityUser copyWith({
    String? id,
    String? username,
    String? avatar,
    String? nickname,
    String? bio,
    int? level,
    int? points,
    int? postCount,
    int? likeCount,
    int? followCount,
    int? fanCount,
    List<String>? badges,
    DateTime? joinDate,
    bool? isVerified,
    bool? isOnline,
    bool? isFollowing,
  }) {
    return CommunityUser(
      id: id ?? this.id,
      username: username ?? this.username,
      avatar: avatar ?? this.avatar,
      nickname: nickname ?? this.nickname,
      bio: bio ?? this.bio,
      level: level ?? this.level,
      points: points ?? this.points,
      postCount: postCount ?? this.postCount,
      likeCount: likeCount ?? this.likeCount,
      followCount: followCount ?? this.followCount,
      fanCount: fanCount ?? this.fanCount,
      badges: badges ?? this.badges,
      joinDate: joinDate ?? this.joinDate,
      isVerified: isVerified ?? this.isVerified,
      isOnline: isOnline ?? this.isOnline,
      isFollowing: isFollowing ?? this.isFollowing,
    );
  }
}

/// 评论模型
class Comment {
  final String id;
  final String postId;
  final CommunityUser author;
  final String content;
  final List<String> images;
  final DateTime createdAt;
  final DateTime updatedAt;
  final int likeCount;
  final bool isLiked;
  final String? parentId;  // 父评论ID（用于回复）
  final List<Comment> replies; // 回复列表

  const Comment({
    required this.id,
    required this.postId,
    required this.author,
    required this.content,
    this.images = const [],
    required this.createdAt,
    required this.updatedAt,
    this.likeCount = 0,
    this.isLiked = false,
    this.parentId,
    this.replies = const [],
  });

  factory Comment.fromJson(Map<String, dynamic> json) {
    return Comment(
      id: json['id'] ?? '',
      postId: json['post_id'] ?? '',
      author: CommunityUser.fromJson(json['author'] ?? {}),
      content: json['content'] ?? '',
      images: List<String>.from(json['images'] ?? []),
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      updatedAt: DateTime.parse(json['updated_at'] ?? DateTime.now().toIso8601String()),
      likeCount: json['like_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      parentId: json['parent_id'],
      replies: (json['replies'] as List<dynamic>? ?? [])
          .map((item) => Comment.fromJson(item))
          .toList(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'post_id': postId,
      'author': author.toJson(),
      'content': content,
      'images': images,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'like_count': likeCount,
      'is_liked': isLiked,
      'parent_id': parentId,
      'replies': replies.map((reply) => reply.toJson()).toList(),
    };
  }
}

/// 帖子模型
class Post {
  final String id;
  final String title;
  final String content;
  final PostType type;
  final PostStatus status;
  final CommunityUser author;
  final List<String> images;
  final List<String> tags;
  final String category;
  final DateTime createdAt;
  final DateTime updatedAt;
  final int viewCount;     // 浏览数
  final int likeCount;     // 点赞数
  final int commentCount;  // 评论数
  final int shareCount;    // 分享数
  final int collectCount;  // 收藏数
  final bool isLiked;      // 是否已点赞
  final bool isCollected;  // 是否已收藏
  final bool isPinned;     // 是否置顶
  final bool isFeatured;   // 是否精选
  final List<Comment> comments; // 评论列表
  final Map<String, dynamic> metadata;

  const Post({
    required this.id,
    required this.title,
    required this.content,
    required this.type,
    required this.status,
    required this.author,
    this.images = const [],
    this.tags = const [],
    this.category = '',
    required this.createdAt,
    required this.updatedAt,
    this.viewCount = 0,
    this.likeCount = 0,
    this.commentCount = 0,
    this.shareCount = 0,
    this.collectCount = 0,
    this.isLiked = false,
    this.isCollected = false,
    this.isPinned = false,
    this.isFeatured = false,
    this.comments = const [],
    this.metadata = const {},
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      content: json['content'] ?? '',
      type: PostType.values.firstWhere(
        (e) => e.name == json['type'],
        orElse: () => PostType.discussion,
      ),
      status: PostStatus.values.firstWhere(
        (e) => e.name == json['status'],
        orElse: () => PostStatus.published,
      ),
      author: CommunityUser.fromJson(json['author'] ?? {}),
      images: List<String>.from(json['images'] ?? []),
      tags: List<String>.from(json['tags'] ?? []),
      category: json['category'] ?? '',
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      updatedAt: DateTime.parse(json['updated_at'] ?? DateTime.now().toIso8601String()),
      viewCount: json['view_count'] ?? 0,
      likeCount: json['like_count'] ?? 0,
      commentCount: json['comment_count'] ?? 0,
      shareCount: json['share_count'] ?? 0,
      collectCount: json['collect_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      isCollected: json['is_collected'] ?? false,
      isPinned: json['is_pinned'] ?? false,
      isFeatured: json['is_featured'] ?? false,
      comments: (json['comments'] as List<dynamic>? ?? [])
          .map((item) => Comment.fromJson(item))
          .toList(),
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
      'type': type.name,
      'status': status.name,
      'author': author.toJson(),
      'images': images,
      'tags': tags,
      'category': category,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'view_count': viewCount,
      'like_count': likeCount,
      'comment_count': commentCount,
      'share_count': shareCount,
      'collect_count': collectCount,
      'is_liked': isLiked,
      'is_collected': isCollected,
      'is_pinned': isPinned,
      'is_featured': isFeatured,
      'comments': comments.map((comment) => comment.toJson()).toList(),
      'metadata': metadata,
    };
  }

  Post copyWith({
    String? id,
    String? title,
    String? content,
    PostType? type,
    PostStatus? status,
    CommunityUser? author,
    List<String>? images,
    List<String>? tags,
    String? category,
    DateTime? createdAt,
    DateTime? updatedAt,
    int? viewCount,
    int? likeCount,
    int? commentCount,
    int? shareCount,
    int? collectCount,
    bool? isLiked,
    bool? isCollected,
    bool? isPinned,
    bool? isFeatured,
    List<Comment>? comments,
    Map<String, dynamic>? metadata,
  }) {
    return Post(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      type: type ?? this.type,
      status: status ?? this.status,
      author: author ?? this.author,
      images: images ?? this.images,
      tags: tags ?? this.tags,
      category: category ?? this.category,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      viewCount: viewCount ?? this.viewCount,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      shareCount: shareCount ?? this.shareCount,
      collectCount: collectCount ?? this.collectCount,
      isLiked: isLiked ?? this.isLiked,
      isCollected: isCollected ?? this.isCollected,
      isPinned: isPinned ?? this.isPinned,
      isFeatured: isFeatured ?? this.isFeatured,
      comments: comments ?? this.comments,
      metadata: metadata ?? this.metadata,
    );
  }

  /// 获取帖子类型显示文本
  String get typeText {
    switch (type) {
      case PostType.discussion:
        return '讨论';
      case PostType.question:
        return '提问';
      case PostType.sharing:
        return '分享';
      case PostType.showcase:
        return '作品展示';
      case PostType.news:
        return '资讯';
      case PostType.event:
        return '活动';
    }
  }

  /// 获取帖子状态显示文本
  String get statusText {
    switch (status) {
      case PostStatus.published:
        return '已发布';
      case PostStatus.draft:
        return '草稿';
      case PostStatus.hidden:
        return '隐藏';
      case PostStatus.deleted:
        return '已删除';
    }
  }

  /// 获取互动总数
  int get totalInteractions {
    return likeCount + commentCount + shareCount + collectCount;
  }

  /// 检查是否有图片
  bool get hasImages {
    return images.isNotEmpty;
  }

  /// 获取内容摘要（前100个字符）
  String get contentSummary {
    if (content.length <= 100) return content;
    return '${content.substring(0, 100)}...';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Post && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'Post{id: $id, title: $title, type: $type, status: $status}';
  }
}

/// 话题模型
class Topic {
  final String id;
  final String name;
  final String description;
  final String icon;
  final String coverImage;
  final int postCount;     // 帖子数量
  final int followCount;   // 关注数量
  final bool isFollowed;   // 是否已关注
  final bool isHot;        // 是否热门
  final DateTime createdAt;
  final List<String> tags;
  final String category;

  const Topic({
    required this.id,
    required this.name,
    this.description = '',
    this.icon = '',
    this.coverImage = '',
    this.postCount = 0,
    this.followCount = 0,
    this.isFollowed = false,
    this.isHot = false,
    required this.createdAt,
    this.tags = const [],
    this.category = '',
  });

  factory Topic.fromJson(Map<String, dynamic> json) {
    return Topic(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      description: json['description'] ?? '',
      icon: json['icon'] ?? '',
      coverImage: json['cover_image'] ?? '',
      postCount: json['post_count'] ?? 0,
      followCount: json['follow_count'] ?? 0,
      isFollowed: json['is_followed'] ?? false,
      isHot: json['is_hot'] ?? false,
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      tags: List<String>.from(json['tags'] ?? []),
      category: json['category'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'icon': icon,
      'cover_image': coverImage,
      'post_count': postCount,
      'follow_count': followCount,
      'is_followed': isFollowed,
      'is_hot': isHot,
      'created_at': createdAt.toIso8601String(),
      'tags': tags,
      'category': category,
    };
  }
}

/// 社区筛选器
enum CommunityFilter {
  all,         // 全部
  following,   // 关注
  hot,         // 热门
  latest,      // 最新
  discussion,  // 讨论
  question,    // 提问
  sharing,     // 分享
  showcase,    // 作品展示
  news,        // 资讯
  event,       // 活动
}

/// 社区筛选器扩展
extension CommunityFilterExtension on CommunityFilter {
  String get displayName {
    switch (this) {
      case CommunityFilter.all:
        return '全部';
      case CommunityFilter.following:
        return '关注';
      case CommunityFilter.hot:
        return '热门';
      case CommunityFilter.latest:
        return '最新';
      case CommunityFilter.discussion:
        return '讨论';
      case CommunityFilter.question:
        return '提问';
      case CommunityFilter.sharing:
        return '分享';
      case CommunityFilter.showcase:
        return '作品展示';
      case CommunityFilter.news:
        return '资讯';
      case CommunityFilter.event:
        return '活动';
    }
  }
}